package com.jrx.anytxn.atom.service.impl;

import com.jrx.anytxn.atom.bean.CustBatchSaveBean;
import com.jrx.anytxn.atom.service.BaseBatchAccoutHandle;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanAccountInfo;
import com.jrx.anytxn.transaction.entity.AmRepaymentPlanInfo;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @program: anytxn-cf-parent
 * @description: 客户批量-客户余额处理
 * @author: liuzb
 * @date: 2022-06-15 18:10
 **/
@Order(220)
@Service
public class CustBalanceHandle extends BaseBatchAccoutHandle<AmLoanAccountInfo> {

    Logger logger = LoggerFactory.getLogger(CustBalanceHandle.class);


    /**
     * 更新未客户余额逻辑处理
     *
     * @return
     * @throws TxnException
     */
    @Override
    public List<AmLoanAccountInfo> handBatchAccout() throws TxnException {
        try {
            CustBatchSaveBean custBatchSaveBean = CustBatchHelper.getCustBatchLocal();
            List<AmLoanAccountInfo> dealLoanAccountList = custBatchSaveBean.getDealLoanAccountList();
            List<AmRepaymentPlanInfo> dealPlanList = custBatchSaveBean.getDealPlanList();
            List<AmLoanAccountInfo> updateLoanList = new ArrayList<>();
            Predicate<AmRepaymentPlanInfo> status = acct ->
                    TransBizConstant.LOAN_PLAN_STATUS_0.equals(acct.getPlanStatus())
                            || TransBizConstant.LOAN_PLAN_STATUS_1.equals(acct.getPlanStatus())
                            || TransBizConstant.LOAN_PLAN_STATUS_2.equals(acct.getPlanStatus());

            if (CollectionUtils.isNotEmpty(dealLoanAccountList)) {
                for (AmLoanAccountInfo acc : dealLoanAccountList) {
                    //正常本金 所有已抛未还本金 （不包含逾期本金）
                    BigDecimal principal = BigDecimal.ZERO;
                    //逾期本金
                    BigDecimal ovdrPrincipal = BigDecimal.ZERO;
                    if (TransBizConstant.ACCOUNT_STATUS_0.equals(acc.getAccountStatus()) || TransBizConstant.ACCOUNT_STATUS_1.equals(acc.getAccountStatus())) {
                        principal = principal.add(acc.getRemainPrincipal());
                    } else if (TransBizConstant.ACCOUNT_STATUS_2.equals(acc.getAccountStatus())) {
                        //逾期
                        List<AmRepaymentPlanInfo> planInfoList = dealPlanList.stream()
                                .filter(status)
                                .filter(p -> acc.getLoanId().equalsIgnoreCase(p.getLoanId()))
                                .collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(planInfoList)) {
                            //逾期部分还款计划
                            for (AmRepaymentPlanInfo plan : planInfoList) {
                                if (TransBizConstant.LOAN_PLAN_STATUS_2.equals(plan.getPlanStatus())) {
                                    //当前本金 - 已还本金
                                    BigDecimal overPrincipal = plan.getPrincipalAmount().subtract(plan.getRepayPrincipal());
                                    ovdrPrincipal = ovdrPrincipal.add(overPrincipal);
                                } else {
                                    BigDecimal prin = plan.getPrincipalAmount().subtract(plan.getRepayPrincipal());
                                    principal = principal.add(prin);
                                }
                            }
                        }
                    }
                    // 设置正常本金余额
                    acc.setNormalPrinBal(principal);
                    // 设置逾期本金余额
                    acc.setOvduePrinBal(ovdrPrincipal);
                    updateLoanList.add(acc);
                }
            }
            logger.info("用户:{},需要处理的订单：{},总的余额:{}",
                    custBatchSaveBean.getDealCust().getCustomerId(),
                    dealLoanAccountList.stream().map(AmLoanAccountInfo::getLoanId).collect(Collectors.joining(",")),
                    dealPlanList.stream().map(plan -> plan.getPrincipalAmount().subtract(plan.getRepayPrincipal())).reduce(BigDecimal.ZERO, BigDecimal::add)
            );
            return updateLoanList;
        } catch (Exception e) {
            logger.warn("统计客户余额发生异常:{}", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
